package com.cloudcentral.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cloudcentral.entity.query.DetectResultQuery;
import com.cloudcentral.entity.vo.PageVO;
import com.cloudcentral.exception.FailureException;
import com.cloudcentral.entity.DetectResult;
import com.cloudcentral.mapper.DetectResultMapper;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 探测结果记录表 服务实现类
 * </p>
 *
 * @author Administrator
 * @since 2023-11-23
 */
@Slf4j
@Service
public class DetectResultService extends ServiceImpl<DetectResultMapper, DetectResult> {
  @Transactional(rollbackFor = {Exception.class})
  @GlobalTransactional(rollbackFor = {Exception.class})
  public void submit(DetectResult detectResult) throws FailureException {
    if (detectResult.getDetectId() == null) throw new FailureException("缺少任务ID");
    else if (detectResult.getFrequency() == null) throw new FailureException("缺少频率");
    else if (StringUtils.isBlank(detectResult.getData())) throw new FailureException("缺少数据");
    else save(detectResult);
  }

  public List<Map<String, Object>> listByIdsCustom(String ids) {
    return baseMapper.listByIdsCustom(ids).stream().peek(detect -> {
      detect.putAll(JSON.parseObject(detect.get("data").toString()));
      detect.remove("data");
    }).collect(Collectors.toList());
  }

  public PageVO<Map<String, Object>> listPage(DetectResultQuery query) {
    IPage<Map<String, Object>> iPage = baseMapper.listPage(new Page<>(query.getPage(), query.getSize()), query);
    return new PageVO<>(iPage.getRecords().stream().peek(detect -> {
      detect.putAll(JSON.parseObject(detect.get("data").toString()));
      detect.remove("data");
    }).collect(Collectors.toList()), iPage.getTotal());
  }
}
